package com.lianniu.mgr.teaNews.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.lianniu.mgr.base.BaseResult;
import com.lianniu.mgr.teaInfo.dao.TeaFrontusersDao;
import com.lianniu.mgr.teaInfo.model.TeaFrontusers;
import com.lianniu.mgr.teaInfo.service.ITeaInfoService;
import com.lianniu.mgr.teaInfo.service.impl.TeaInfoServiceImpl;
import com.lianniu.mgr.teaNews.dao.TeaNewsMapper;
import com.lianniu.mgr.teaNews.model.TeaNews;
import com.lianniu.mgr.teaNews.service.ITeaNewsService;
import com.lianniu.mgr.util.DateUtil;
import com.lianniu.mgr.util.UUIDUtil;



@Service
@Transactional
public class TeaNewsServiceImpl implements ITeaNewsService {

	private final static Logger logger = Logger.getLogger(TeaNewsServiceImpl.class);
	
	@Autowired
	private TeaNewsMapper teaNewsMapper;
	@Autowired
	private TeaFrontusersDao teaFrontusersDao;
	
	@Override
	public BaseResult getUserNewsList(TeaNews teaNews) {
		logger.info("TeaNewsServiceImpl getUserNewsList start");
		Long userId = teaNews.getUserId();
		List<TeaNews> teaUserList = teaNewsMapper.getUserNewsListByUserId(userId);
		logger.info("TeaNewsServiceImpl getUserNewsList end");
		return BaseResult.success(teaUserList);
	}

	@Override
	public BaseResult saveUserNews(TeaNews teaNews,String userIds) {
		try {
			logger.info("TeaNewsServiceImpl insertUserNews start");
			if(StringUtils.isNotEmpty(userIds)){
				String[] ids = userIds.split(",");
				for (String id : ids) {
					teaNews.setUserId(Long.valueOf(id));
					teaNews.setNewsCreateTime(DateUtil.getNowTime());
					teaNews.setId(UUIDUtil.getUUID());
					teaNewsMapper.insert(teaNews);
				}
			}else{
				List<TeaFrontusers> users = teaFrontusersDao.selectAllUsers();
				if(!CollectionUtils.isEmpty(users)){
					for (TeaFrontusers teaFrontusers : users) {
						teaNews.setUserId(teaFrontusers.getUsersid());
						teaNews.setNewsCreateTime(DateUtil.getNowTime());
						teaNews.setId(UUIDUtil.getUUID());
						teaNewsMapper.insert(teaNews);
					}
				}
			}
			logger.info("TeaNewsServiceImpl insertUserNews end");
			return BaseResult.success("ok");
		} catch (Exception e) {
			return BaseResult.success("fail");
		}
	
	}

}
